<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->headTitle()->prepend($this->view->translate('profile data'));
        $user = Zend_Auth::getInstance()->getStorage()->read();
        if (!$user and $this->getRequest()->getActionName() != 'register')
        $this->_forward ( 'register' );

    }

    public function indexAction()
    {
        $this->_forward ( 'register' );
    }

    public function registerAction()
    {
        $this->view->registerForm = $this->getRegistrationForm();
        if ($this->getRequest()->isPost())
        {
            if ($this->view->registerForm->isValid($_POST))
            {
                $values = $this->view->registerForm->getValues();
                $this->view->values = $values;
            }
        }
    }

    public function activateAction()
    {
    }

    private function getRegistrationForm()
    {
        $form = new Zend_Form ( );

        $form->setAction ( $this->view->baseScript.'/register' )->setMethod ( 'post' )->setAttrib ( 'id', 'register' );

        $username = new Zend_Form_Element_Text ( 'username' );
        $validatorAlnum = new Zend_Validate_Alnum ( );
        $username->setRequired ( true )->setLabel ( 'Username' );
        $form->addElement ( $username );

        $submit = new Zend_Form_Element_Submit ( 'register' );
        $submit->setLabel ( 'Submit' );
        $form->addElement ( $submit );

        return $form;
    }

    public function lostPasswordAction()
    {
    }

    public function profileAction()
    {
        $form = new Default_Form_Profile();
        $user = Zend_Auth::getInstance()->getStorage()->read();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getParams())) {
                // 檢查舊密是否正確 -
                $res = Doctrine_Query::create()
                ->select('id')
                ->from('Default_Model_Users')
                ->where('id=?',$user->id)
                ->andWhere('password=?',  $this->_helper->PassOperate($form->getValue('oldPassword')))
                ->fetchOne();
                if (!$res) {
                    $form->addErrorMessage($this->view->translate('old password not match'));
                }
                else {
                      // 更新個人資料
                      Doctrine_Query::create()
                      ->update('Default_Model_Users')
                      ->set('password','?', $this->_helper->PassOperate($form->getValue('password')))
                      ->set('email', '?', $form->getValue('email'))
                      ->where('id =?', $user->id)
                      ->execute();
                    $this->view->message = $this->view->translate('edit success');
                }
            }
        }
        else
        $form->setDefault('email', $user->email);

        $this->view->form = $form;
    }


}

